Ext.ns("sys");

sys.QuerySegmentForm = Ext.extend(Ext.form.FormPanel, {
	constructor : function(cfg) {
		Ext.apply(this, cfg || {});

		this.segmentId = new Ext.form.Hidden({
			fieldLabel : 'id',
			name : 'id'
		});
		this.segmentOrder = new Ext.form.Hidden({
			fieldLabel : 'segmentOrder',
			name : 'segmentOrder'
		});
		this.queryUnitId = new Ext.form.Hidden({
			fieldLabel : 'queryUnit.id',
			name : 'queryUnit.id'
		});
		this.condition = new Ext.form.TextArea({
			fieldLabel : '条件',
			name : 'condition',
			height : 60,
			allowBlank : false
		});
		this.text = new Ext.form.TextArea({
			fieldLabel : '内容',
			height : 60,
			name : 'text'
		});

		this.resetBtn = new Ext.Button({
			text : '重置',
			handler : function() {
				this.reset();
			},
			scope : this
		});
		this.saveBtn = new Ext.Button({
			text : '新建',
			formBind : false,
			handler : function() {
				this.form.doAction('submit', {
					url : '../../query/saveQuerySegment.do',
					method : 'POST',
					scope : this,
					success : function(form, action) {
						this.reset();
						this.querySegmentPanel.querySegmentGrid.refresh();
					},
					failure : function(form, action) {
						switch (action.failureType) {
						case Ext.form.Action.CLIENT_INVALID:
							Ext.Msg.alert("提示", "提交数据无效");
							break;
						case Ext.form.Action.CONNECT_FAILURE:
							Ext.Msg.alert("提示", "与服务器连接失败");
							break;
						case Ext.form.Action.SERVER_INVALID:
							Ext.Msg.alert("提示", action.result.msg);
						}
					}
				});
			},
			scope : this
		});
		this.reset = function() {
			var vals = this.form.getValues();
			this.form.reset();
			this.form.setValues({
				'queryUnit.id' : vals['queryUnit.id']
			});
			this.saveBtn.setText('新建');
		};

		this.edit = function(rec) {
			this.form.loadRecord(rec);
			this.saveBtn.setText('保存');
		};

		sys.QuerySegmentForm.superclass.constructor.call(this, {
			id : '_query_segment_form',
			baseCls : 'x-plain',
			labelAlign : 'right',
			labelWidth : 60,
			bodyStyle : "padding: 5px 5px 5px 5px;",
			monitorValid : true,
			defaults : {
				width : 300
			},
			items : [ this.segmentId, this.segmentOrder, this.queryUnitId,
					this.condition, this.text ],
			buttons : [ this.resetBtn, this.saveBtn ],
			listeners : {
				'clientvalidation' : {
					fn : function(formPanel, valid) {
						this.saveBtn.setDisabled(!valid || !this.queryUnitId.getValue());
					},
					scope : this
				}
			}
		});
	}
});

sys.QuerySegmentGrid = Ext.extend(Ext.grid.GridPanel, {
	constructor : function(cfg) {
		Ext.apply(this, cfg || {});
		this.refreshBtn = new Ext.Button({
			text : '刷新',
			iconCls : 'refresh',
			handler : function() {
				this.refresh();
			},
			scope : this
		});
		this.delBtn = new Ext.Button({
			text : '删除',
			iconCls : 'del',
			disabled : true,
			verify : function(sm) {
				return sm.getSelections().length > 0;
			},
			handler : function() {
				var ids = this.getSelectedIds();
				Ext.Msg.confirm('提示', '是否删除选中项,共[' + ids.length + ']条', function(msg) {
					if (msg == 'yes') {
						Ext.Ajax.request({
							url : '../../query/delQuerySegments.do',
							method : 'POST',
							success : function(resp, opt) {
								this.refresh();
							},
							params : {
								ids : ids
							},
							scope : this
						});
					}
				}, this);
			},
			scope : this
		});
		this.searcher = new Ext.form.TwinTriggerField({
			width : 150,
			trigger1Class : 'x-form-clear-trigger',
			trigger2Class : 'x-form-search-trigger',
			hideTrigger1 : true,
			emptyText : '输入关键字查询',
			hasSearch : false,
			grid : this,
			onTrigger1Click : function(e) {
				if (this.hasSearch) {
					this.el.dom.value = '';
					var text = this.getValue();
					Ext.apply(this.grid.getStore().baseParams, {
						queryText : text
					});
					this.grid.refresh(0);
					this.hasSearch = false;
					this.triggers[0].hide();
				}
			},
			onTrigger2Click : function(e) {
				var text = this.getValue();
				if (text.length < 1) {
					this.onTrigger1Click();
					return;
				} else {
					Ext.apply(this.grid.getStore().baseParams, {
						queryText : text
					});
				}
				this.grid.refresh(0);
				this.hasSearch = true;
				this.triggers[0].show();

			},
			listeners : {
				'specialkey' : {
					fn : function(fild, e) {
						if (e.getKey() == e.ENTER) {
							this.searcher.onTrigger2Click.call(this.searcher);
						}
					},
					scope : this
				}
			}
		});
		this.store = new Ext.data.JsonStore({
			url : '../../query/query.do',
			method : 'POST',
			baseParams : {
				type : 'hql',
				text : 'from QuerySegment qs where 1=1',
				'querySegments[0].condition' : 'key!=void',
				'querySegments[0].text' : "and qs.queryUnit.key='${key}'",
				'querySegments[1].condition' : '1==1',
				'querySegments[1].text' : "order by qs.segmentOrder"
			},
			fields : [ 'id', 'condition', 'text', 'queryUnit.id', 'queryUnit.key',
					'segmentOrder' ],
			listeners : {
				'beforeload' : {
					fn : function(store, opts) {
						var configPanel = this.querySegmentPanel.queryConfigPanel;
						var unitGrid = configPanel.queryUnitPanel.queryUnitGrid;
						var rec = unitGrid.getSelected();
						if (!rec) {
							store.removeAll();
							return false;
						} else {
							Ext.apply(opts.params, {
								key : rec.data['key']
							});
						}
					},
					scope : this
				}
			}
		});
		this.csm = new Ext.grid.CheckboxSelectionModel({
			listeners : {
				'selectionchange' : {
					fn : function(sm) {
						this.querySegmentPanel.querySegmentForm.reset();
						var rec = sm.getSelected();
						if (rec) {
							this.querySegmentPanel.querySegmentForm.edit(rec);
						}
						Ext.each(this.getTopToolbar().items.getRange(), function(item,
								index, all) {
							if (item.verify) {
								item.setDisabled(!item.verify(sm));
							}
						}, this);
					},
					scope : this
				}
			}
		});

		this.cm = new Ext.grid.ColumnModel({
			defaults : {
				sortable : true,
				width : 100
			},
			columns : [ new Ext.grid.RowNumberer(),this.csm, {
				id : 'condition',
				header : '条件',
				dataIndex : 'condition'
			}, {
				id : 'text',
				header : '内容',
				dataIndex : 'text'
			} ]
		});
		this.refresh = function() {
			this.getSelectionModel().clearSelections();
			this.getStore().reload();
		};
		this.getSelected = function() {
			return this.getSelectionModel().getSelected();
		};
		this.getSelections = function() {
			return this.getSelectionModel().getSelections();
		};
		this.getSelectedIds = function() {
			var ids = [];
			var records = this.getSelectionModel().getSelections();
			if (!records)
				return ids;
			for ( var i = 0; i < records.length; i++) {
				ids.push(records[i].data.id);
			}
			return ids;
		};

		sys.QuerySegmentGrid.superclass.constructor.call(this, {
			id : '_query_segment_grid',
			store : this.store,
			loadMask : true,
			stripeRows : true,
			enableDragDrop : true,
			ddGroup : 'ddGroup',
			sm : this.csm,
			cm : this.cm,
			autoExpandColumn : 'text',
			tbar : [ this.delBtn ],
			listeners : {
				'render' : {
					fn : function() {
						this.refresh();
						var ddrow = new Ext.dd.DropTarget(this.getView().scroller.dom, {
							ddGroup : 'ddGroup',
							notifyDrop : function(ddSource, e, data) {
								var records = ddSource.dragData.selections;
								var index = ddSource.getDragData(e).rowIndex;
								if (typeof (index) == 'undefined') {
									return false;
								}
								if (records.length != 1) {
									return false;
								}
								var rec = records[0];
								var id = rec.data['id'];
								Ext.Ajax.request({
									url : '../../query/moveQuerySegment.do',
									method : 'POST',
									params : {
										id : id,
										index : index
									},
									success : function(resp, opt) {
										ddSource.grid.refresh();
									},
									scope : this
								});
								return true;
							}
						});
					},
					scope : this
				}
			}
		});
	}

});

sys.QuerySegmentPanel = Ext.extend(Ext.Panel, {
	constructor : function(cfg) {
		Ext.apply(this, cfg || {});
		this.querySegmentForm = new sys.QuerySegmentForm({
			region : 'center',
			querySegmentPanel : this
		});
		this.querySegmentGrid = new sys.QuerySegmentGrid({
			title : '动态查询条件段列表',
			region : 'center',
			querySegmentPanel : this
		});
		sys.QuerySegmentPanel.superclass.constructor.call(this, {
			id : '_query_segment_panel',
			layout : 'border',
			title : '动态查询条件段信息',
			split : true,
			collapsible : true,
			items : [ {
				title : '编辑查看',
				region : 'north',
				height : 240,
				layout : 'border',
				split : true,
				collapsible : true,
				items : [ this.querySegmentForm ]
			}, this.querySegmentGrid ]
		});
	}
});